package com.spzx.payment.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.order.api.RemoteOrderInfoService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.payment.configure.AlipayConfig;
import com.spzx.payment.domain.PaymentInfo;
import com.spzx.payment.service.IAlipayService;
import com.spzx.payment.service.IPaymentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;

@Service
public class AlipayServiceImpl implements IAlipayService {

    @Autowired
    AlipayClient alipayClient;

    @Autowired
    IPaymentInfoService paymentInfoService;

    @Autowired
    private RemoteOrderInfoService remoteOrderInfoService;

    @Override
    public String submitAlipay(String orderNo) {
        //保存支付记录
        PaymentInfo paymentInfo= paymentInfoService.savePaymentInfo(orderNo);
        //构建支付请求对象
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        //同步回调地址
        request.setReturnUrl(AlipayConfig.return_payment_url);//支付成功
        //异步回调地址
        request.setNotifyUrl(AlipayConfig.notify_payment_url);
        //支付宝接口传递数据
        HashMap<String,Object> map=new HashMap<>();
        map.put("out_trade_no",paymentInfo.getOrderNo());//订单号
        map.put("product_code","QUICK_WAP_WAY");//商家和支付宝签约的产品码
//        真实的金额 远程调用order接口
//        慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用
//        R<OrderInfo> orderInfoResult = remoteOrderInfoService.getByOrderNo(orderNo, SecurityConstants.INNER);
//        OrderInfo orderInfo = orderInfoResult.getData();
//        BigDecimal totalAmount = orderInfo.getTotalAmount();
//        map.put("total_amount",totalAmount);
//        慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用  慎用

        map.put("total_amount",0.01);
        map.put("subject",paymentInfo.getContent());//交易内容
        request.setBizContent(JSON.toJSONString(map));
        try {
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request, "POST");
            return response.getBody();//获取支付宝返回 h5 form表单
        } catch (AlipayApiException e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
